package stackandqueue.stack.link;


/**
 * 单链表的操作
 * @author tianzhuang
 * @version 1.0
 * @date 2021/11/12 18:22
 */
public class MyLink {
    Node head = null;

    class Node{
        private int val;
        private Node next;

        public Node(int val) {
            this.val = val;
        }
    }

    /**
     * 添加一个节点
     * @param val
     */
    public void addNode(int val) {
        Node node = new Node(val);
        // 如果头节点为空，则将添加的节点赋值给头节点
        if (head == null) {
            head = node;
            return;
        }
        // 从头节点开始遍历，直到遍历到最后一个节点。
        Node tmp = head;
        while (tmp.next != null) {
            tmp = tmp.next;
        }
        // 将最后一个节点的next值指向新添加的节点
        tmp.next = node;
    }

    /**
     * 返回链表长度
     * @return
     */
    public int length() {
        int i = 0;
        if (head != null) {
            i++;
        }
        Node tmp = head;
        while (tmp.next != null) {
            i++;
            tmp = tmp.next;
        }
        return i;
    }


    /**
     * 删除指定位置的节点
     * @param index
     */
    public Boolean delNode(Integer index) {
        if (index < 1 || index > length()) {
            System.err.println("位置错误");
            return false;
        }
        if (index-1 == 0) {
            head = head.next;
            return true;
        }
        Node tmp = head;
        int i = 1;
        while (tmp.next != null) {
            i++;
            if (i == index) {
                // 必须使用 .next = .next.next
                tmp.next = tmp.next.next;
                return true;
            }
            tmp = tmp.next;
        }
        return false;
    }

    /**
     * 打印链表
     */
    public void printNode() {
        Node tmp = head;
        while (tmp != null) {
            System.err.println(tmp.val);
            tmp = tmp.next;
        }
    }

    public static void main(String[] args) {
        MyLink myLink = new MyLink();
        myLink.addNode(4);
        myLink.addNode(6);
        myLink.addNode(2);
        myLink.addNode(5);
        myLink.addNode(9);
//        myLink.printNode();
        Boolean aBoolean = myLink.delNode(5);
        System.err.println(aBoolean);
        myLink.printNode();
    }

}
